#include "lm_conf_ipcamera_wrapper.h"

namespace lm {
	void CALLBACK FuncIPCameraOnSearchWithLANCB(
		int error, const LMIPCameraAddress* results, int count, void* clientdata) {
		ConfIPCameraWrapper* wrapper = reinterpret_cast<ConfIPCameraWrapper*>(clientdata);
		wrapper->OnSearchWithLANCB(error, results, count);
	}

	void CALLBACK FuncIPCameraOnAddIPCameraCB(
		int error, int identity, const LMIPCameraInfo* info, void* clientdata) {
		ConfIPCameraWrapper* wrapper = reinterpret_cast<ConfIPCameraWrapper*>(clientdata);
		wrapper->OnAddIPCameraCB(error, identity, info);
	}

	void ConfIPCameraWrapper::OnSearchWithLANCB(int error, const LMIPCameraAddress* results, int count) {
		for (ObserverList::iterator it = observer_list_.begin(); it != observer_list_.end(); it++) {
			(*it)->OnSearchWithLAN(error, results, count);
		}
	}

	void ConfIPCameraWrapper::OnAddIPCameraCB(int error, int identity, const LMIPCameraInfo* info) {
		for (ObserverList::iterator it = observer_list_.begin(); it != observer_list_.end(); it++) {
			(*it)->OnAddIPCamera(error, identity, info);
		}
	}

	ConfIPCameraWrapper::ConfIPCameraWrapper(native_object_t c_object)
		: c_object_(c_object) {
		ConfIPCameraCallback cb;
		memset(&cb, 0, sizeof(cb));
		cb.client_data_ = this;
		cb.OnAddIPCamera_ = FuncIPCameraOnAddIPCameraCB;
		cb.OnSearchWithLAN_ = FuncIPCameraOnSearchWithLANCB;
		lm_conf_ipcamera_set_callback(c_object_, &cb);
	}

	ConfIPCameraWrapper::~ConfIPCameraWrapper() {
	}

	void ConfIPCameraWrapper::AddObserver(Observer* observer) {
		if (std::find(observer_list_.begin(), observer_list_.end(), observer) == observer_list_.end())
			observer_list_.push_back(observer);
	}

	void ConfIPCameraWrapper::RemoveObserver(Observer* observer) {
		ObserverList::iterator it = std::find(observer_list_.begin(), observer_list_.end(), observer);
		if (it != observer_list_.end())
			observer_list_.erase(it);
	}

	int ConfIPCameraWrapper::SearchWithLAN(const char* multicast_address/* = "239.255.255.250:3702"*/) {
		return lm_conf_ipcamera_SearchWithLAN(c_object_, multicast_address);
	}

	int ConfIPCameraWrapper::AddIPCamera(
		const LMIPCameraAddress* address,
		const LMIPCameraAuthInfo* auth,
		int* identity) {
		return lm_conf_ipcamera_AddIPCamera(c_object_, address, auth, identity);
	}

	int ConfIPCameraWrapper::RemoveIPCamera(int identity) {
		return lm_conf_ipcamera_RemoveIPCamera(c_object_, identity);
	}
}